import json
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

# 加载JSON数据
with open('data.json', 'r') as json_file:
    data = json.load(json_file)

# 创建XML的根元素
annotation = Element('annotation')

# 设置文件夹名称
folder = SubElement(annotation, 'folder')
folder.text = 'VOC2007'

# 设置文件名
filename = SubElement(annotation, 'filename')
filename.text = data['imagePath']

# 设置来源数据库信息
source = SubElement(annotation, 'source')
database = SubElement(source, 'database')
database.text = 'Unknown'
annotation_ = SubElement(source, 'annotation')
annotation_.text = 'Unknown'
image = SubElement(source, 'image')
image.text = 'Unknown'
flickrid = SubElement(source, 'flickrid')
flickrid.text = 'Unknown'

# 设置图像尺寸
size = SubElement(annotation, 'size')
width = SubElement(size, 'width')
width.text = str(data['imageWidth'])
height = SubElement(size, 'height')
height.text = str(data['imageHeight'])
depth = SubElement(size, 'depth')
depth.text = '3'

# 设置是否分割的标注
segmented = SubElement(annotation, 'segmented')
segmented.text = '0'

# 遍历JSON中的形状并创建XML对象
for shape in data['shapes']:
    obj = SubElement(annotation, 'object')
    name = SubElement(obj, 'name')
    name.text = shape['label']

    # 假设所有对象的姿态都是未指定的
    pose = SubElement(obj, 'pose')
    pose.text = 'Unspecified'

    # 假设所有对象都没有被截断
    truncated = SubElement(obj, 'truncated')
    truncated.text = '0'

    # 假设所有对象都不难识别
    difficult = SubElement(obj, 'difficult')
    difficult.text = '0'

    bndbox = SubElement(obj, 'bndbox')
    xmin = SubElement(bndbox, 'xmin')
    xmin.text = str(min(x[0] for x in shape['points']))
    ymin = SubElement(bndbox, 'ymin')
    ymin.text = str(min(x[1] for x in shape['points']))
    xmax = SubElement(bndbox, 'xmax')
    xmax.text = str(max(x[0] for x in shape['points']))
    ymax = SubElement(bndbox, 'ymax')
    ymax.text = str(max(x[1] for x in shape['points']))

# 添加注释和处理指令
annotation_str = tostring(annotation)
output_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + annotation_str.decode('utf-8')

# 保存到XML文件
with open('output.xml', 'w') as xml_file:
    xml_file.write(output_str)